import java.io.*;
import java.util.Iterator;
import javax.servlet.*;
import javax.servlet.http.*;

public class PizzaServlet extends CommonServlet {
	private static final long serialVersionUID = 1L;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.doGet(request, response);
		System.out.println("PizzaServlet.doGet()");
		
		session.setAttribute("previous", "");
		
		if(pb.get("error") != null) {
			request.setAttribute("error",pb.get("error"));
		}
		
		pb.clear();
		
		if(nb.get("name") != null) {
			pb.put("welcome", "Welkom, "+nb.get("name"));
		}

		pb.put("select", pb.getSelect());
		request.setAttribute("ingredients", pb.getIngredients());
		
		
		request.setAttribute("pb", pb);
		//pb.populate(request, pb);
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Pizza.jsp");
		dispatcher.forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//super.doPost(request, response, pb);
		System.out.println("PizzaServlet.doPost()");
		
		//TODO: moet dit: ?
		request.setAttribute("pb", pb);
		pb.populate(request, pb);

		String pizza = "";
		String price = "";

		if(!pb.containsKey("ingredients")) {
			 pizza = pb.get("pizza");
			 price = pb.formatPrice(pb.pizzas.get(pizza));
			 
		} else {
			pizza = "Samengestelde pizza (";
			
			double prc = 6.50;
			
			Iterator<String> it = pb.keySet().iterator();
			while(it.hasNext()) {
				String entry = it.next();
				if(entry.startsWith("ingredients-") && !pb.get(entry).equals("on")) {
					pizza+=entry.substring(12)+", ";
					prc += pb.ingredients.get(entry.substring(12));
				}
			}
			
			pizza = pizza.substring(0, pizza.length()-2) + ")";
			
			if(prc == 6.50) {
				pizza=null;
			}
			
			price = pb.formatPrice(prc)+"";
		}
		
		if(pizza == null || pizza.equals("")) {
			pb.put("error", "Er is geen pizza geselecteerd.");
			
			// Geen pizza, dus weer doGet
			doGet(request, response);
		} else {
			pb.put("pizza", pizza);
			pb.put("price", price);

			session.setAttribute("pb", pb);
			
			// Pizza selected, dus naar volgende
			session.setAttribute("previous", "pizza");
			response.sendRedirect("name");
		}
	}
}